<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>OAuth Server Login</title>
    <link rel="stylesheet" href="/bootstrap/css/bootstrap.min.css">
</head>

<body>
<section class="h-100">
    <div class="container h-100">
        <div class="row justify-content-sm-center h-100">
            <div class="col-xxl-4 col-xl-5 col-lg-5 col-md-7 col-sm-9">
                <div class="text-center my-5">
                    <img src="/images/Pokemon.webp" alt="logo" width="100">
                </div>
                <div class="card shadow-lg">
                    <div class="card-body p-5">
                        <h1 class="fs-4 card-title fw-bold mb-4">登录</h1>
                        <form action="/login" method="post" class="needs-validation" novalidate="" autocomplete="off"
                              id="loginForm">
                            <div class="mb-3">
                                <label class="mb-2 text-muted" for="email">账号</label>
                                <input id="username" type="text" class="form-control" name="username" value=""
                                       required autofocus>
                                <div class="invalid-feedback">
                                    无效账号
                                </div>
                            </div>
                            <input type="hidden" name="_csrf" id="_csrfToken" th:value="${_csrf.token}">
                            <!--                            <input name="_csrf" type="hidden" value="${_csrf.token}">-->
                            <div class="mb-3">
                                <div class="mb-2 w-100">
                                    <label class="text-muted" for="password">密码</label>
                                    <a href="forgot.html" class="float-end">
                                        忘记密码?
                                    </a>
                                </div>
                                <input id="password" type="password" class="form-control" name="password" required>
                                <div class="invalid-feedback">
                                    密码不能为空
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="mb-2 text-muted" for="imageCode">图片验证码</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" name="verifyCode" required
                                           id="verifyCode">
                                    <img id="imageCodeImg" src="/login/verifyCode" alt="图片验证码"
                                         onclick="refreshImageCode()">
                                </div>
                                <div class="invalid-feedback">
                                    图片验证码不能为空
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="mb-2 text-muted" for="phoneCode">手机验证码</label>

                                <div class="input-group">
                                    <input type="text" class="form-control" name="captcha" id="captcha" required>
                                    <button type="button" class="btn btn-outline-secondary"
                                            onclick="requestPhoneCode()">
                                        申请手机验证码
                                    </button>
                                </div>
                                <div class="invalid-feedback">
                                    手机验证码不能为空
                                </div>
                            </div>
                            <div class="d-flex align-items-center">
                                <button type="submit" class="btn btn-primary ms-auto" onclick="submitForm(event)">
                                    登录
                                </button>
                            </div>
                        </form>
                    </div>
                    <div class="card-footer py-3 border-0">
                        <div class="text-center">
                            还没账号? <a href="register.html" class="text-dark">创建账号</a>
                        </div>
                    </div>
                </div>
                <div class="text-center mt-5 text-muted">
                    Copyright &copy; 2017 - 2021 &mdash; Your Company
                </div>
            </div>
        </div>
    </div>
</section>
<script src="/bootstrap/js/bootstrap.bundle.min.js"></script>
<script>
    async function refreshImageCode() {
        try {
            const response = await fetch('/login/verifyCode');
            const blob = await response.blob();
            const reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onloadend = function () {
                const base64data = reader.result;
                const imageCodeImg = document.getElementById('imageCodeImg');
                imageCodeImg.src = base64data;
            };
        } catch (error) {
            console.error('Error refreshing image code:', error);
        }
    }

    async function requestPhoneCode() {
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const verifyCode = document.getElementById('verifyCode').value;
        if (!username || !password || !verifyCode) {
            alert('账号、密码和图片验证码均为必填项。');
            return;
        }
        const csrfToken = document.getElementById('_csrfToken').value;
        try {
            const response = await fetch('/login/captcha', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify({username, password})
            });
            const data = await response.json();
            // console.log(response);
            // console.log(data);
            if (response.ok) {
                if (data.success) {
                    // 处理成功响应
                    alert(data.errorMessage);
                } else {
                    // 处理错误响应
                    alert(data.errorCode + ":" + data.errorMessage);
                }
            } else {
                // 处理错误响应
                alert(response.status);
            }
        } catch (error) {
            console.error('Error requesting phone code:', error);
        }
    }

    async function submitForm(event) {
        event.preventDefault();
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;
        const verifyCode = document.getElementById('verifyCode').value;
        const captcha = document.getElementById('captcha').value;
        let hasError = false;
        if (!username) {
            document.getElementById('username').classList.add('is-invalid');
            hasError = true;
        } else {
            document.getElementById('username').classList.remove('is-invalid');
        }
        if (!password) {
            document.getElementById('password').classList.add('is-invalid');
            hasError = true;
        } else {
            document.getElementById('password').classList.remove('is-invalid');
        }
        if (!verifyCode) {
            document.getElementById('verifyCode').classList.add('is-invalid');
            hasError = true;
        } else {
            document.getElementById('verifyCode').classList.remove('is-invalid');
        }
        if (!captcha) {
            document.getElementById('captcha').classList.add('is-invalid');
            hasError = true;
        } else {
            document.getElementById('captcha').classList.remove('is-invalid');
        }
        if (hasError) {
            return;
        }
        try {
            const form = document.getElementById('loginForm');
            const formData = new FormData(form);
            const response = await fetch('/login', {
                method: 'POST',
                headers: {
                    // 'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.getElementById('_csrfToken').value
                },
                body: formData
            });
            if (response.status === 200) {
                // 如果响应状态码是 200，假设服务器返回 HTML 页面内容
                const htmlContent = await response.text();
                document.documentElement.innerHTML = htmlContent;
            } else {
                // 如果不是 200，假设服务器返回 JSON 报错信息
                const data = await response.json();
                alert(data.errorCode + ":" + data.errorMessage);
            }
        } catch (error) {
            console.error('Error submitting form:', error);
        }
    }

</script>
</body>

</html>